package dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;

import utils.JDBCUtil;

public class UserDaoImpl implements UserDao {

	public boolean writeUser(User User) {
		Connection conn = null;
		PreparedStatement pstat = null;
		String sql = "insert into login (user_name,user_pw) values (?,?)";//表中有用户名和密码
		int result = -1;
		
		try {
			conn = JDBCUtil.getConnection();
			pstat = conn.prepareStatement(sql);
			pstat.setString(0, User.getName());
			pstat.setString(1, User.getpassWord());
			result = pstat.executeUpdate();
			
		}catch (SQLException sqle) {
			sqle.printStackTrace();
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			JDBCUtil.realeaseAll(null,pstat, conn);
		}
		return result>0?true:false;
	}

	public User readUser(String name) {
		Connection conn = null;
		PreparedStatement pstat = null;
		ResultSet rs = null;
		String sql = "select * from login where user_name like ?";
		User User = null;
		try {
			conn = JDBCUtil.getConnection();
			pstat = conn.prepareStatement(sql);
			pstat.setString(0, user_name);
			rs = pstat.executeQuery();
			while(rs.next()){
				String user_name = rs.getString("user_name");
				String user_pw = rs.getString("user_pw");
				User = new User(user_name,user_pw);
			}
		}catch (SQLException sqle) {
			sqle.printStackTrace();
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			JDBCUtil.realeaseAll(rs,pstat, conn);
		}
		return User;
	}

	@Override
	public void diplayAllUser;() {
		Connection conn = null;
		Statement stat = null;
		ResultSet rs = null;
		String sql = "select * from login";
		try {
			conn = JDBCUtil.getConnection();
			stat = conn.createStatement();
			rs = stat.executeQuery(sql);
			while(rs.next()){
				String user_name = rs.getString("user_name");
				String user_pw = rs.getString("user_pw");
			}
		}catch (SQLException sqle) {
			sqle.printStackTrace();
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			JDBCUtil.realeaseAll(rs,stat, conn);
		}
	}

}
